package com.yachang.qym.usbhost.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.nkzawa.emitter.Emitter;
import com.google.gson.Gson;
import com.squareup.leakcanary.RefWatcher;
import com.yachang.qym.usbhost.R;
import com.yachang.qym.usbhost.UsbApplication;
import com.yachang.qym.usbhost.activity.MessageActivity;
import com.yachang.qym.usbhost.model.CallHelpModel;
import com.yachang.qym.usbhost.model.HelpModel;
import com.yachang.qym.usbhost.model.OutPoliceModel;
import com.yachang.qym.usbhost.utils.API;
import com.yachang.qym.usbhost.utils.AllData;
import com.yachang.qym.usbhost.utils.DataTransfer;
import com.yachang.qym.usbhost.utils.LoadImage;
import com.yachang.qym.usbhost.utils.SendData;
import com.yachang.qym.usbhost.utils.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.yachang.qym.usbhost.utils.API.mSocket;

/**
 * Created by qinyuanmao on 16/3/8.
 */
public class HighFragment extends Fragment{

    private View mParentView;
    private TextView mTvHighId;
    private TextView mTvHighHigh;
    private TextView mTvHighTemperature;
    private TextView mTvHighFloor;
    private TextView mTvHelpId;
    private TextView mTvHelpHigh;
    private TextView mTvHelpTemperature;
    private TextView mTvHelpFloor;
    private TextView mTvHelpDistance;
    private TextView mTvHelpError;
    private LinearLayout mHelpInfoParent;
    private TextView mTvEnter, mTvExit;
    private RelativeLayout mLayoutEnter, mLayoutExit, mBtnVideo;
    private TextView mBtnStopHelp, mBtnFinishHelp;
    private CircleImageView mIvMy, mIvHim;
    private Spinner mFirstFloor, mFloorHigh;
    private List<String> mListFloorHigh = new ArrayList<>();
    private List<String> mListFirstFloor = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg){
          switch (msg.what){
              case 0:initData();break;
              default:break;
          }
      }
    };

    private Emitter.Listener onPolice = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(AllData.isToHelp){
                            OutPoliceModel data = new OutPoliceModel();
                            Gson gson = new Gson();
                            JSONObject jsonObject = (JSONObject) args[0];
                            data = gson.fromJson(String.valueOf(jsonObject), OutPoliceModel.class);
                            if(data.get_id().equals(AllData.callHelpModel.getOid())){
                                if(AllData.isFirstLoad){
                                    mIvMy.setImageBitmap(AllData.userBitmap.get(AllData.userModel.get_id()));
                                    mHelpInfoParent.setVisibility(View.VISIBLE);
                                    mIvHim.setImageBitmap(AllData.userBitmap.get(data.getUid()));
                                    mTvHelpId.setText(data.getUserName());
                                    AllData.isFirstLoad = false;
                                }
                                mTvHelpHigh.setText(data.getHigh() + "");
                                mTvHelpFloor.setText(data.getNowFloor() + "");
                                mTvHelpTemperature.setText(data.getTemp() + "");
                            }
                        }
                    }
                });
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mParentView = inflater.inflate(R.layout.fragment_high, container, false);
        initView();
        initData();
        SetDataThread thread = new SetDataThread();
        thread.start();
        mSocket.on("address", onPolice);
        String[] firstFloor = getResources().getStringArray(R.array.first_floor_detail);
        for(int i = 0; i < firstFloor.length; i++){
            mListFirstFloor.add(firstFloor[i]);
        }
        String[] floorHigh = getResources().getStringArray(R.array.floor_high_detail);
        for(int i = 0; i < floorHigh.length; i++){
            mListFloorHigh.add(floorHigh[i]);
        }

        return mParentView;
    }

    private void initView() {
        mTvHighId = (TextView) mParentView.findViewById(R.id.tv_high_id);
        mTvHighHigh = (TextView) mParentView.findViewById(R.id.tv_high_high);
        mTvHighTemperature = (TextView) mParentView.findViewById(R.id.tv_high_temperature);
        mTvHighFloor = (TextView) mParentView.findViewById(R.id.tv_high_floor);
        mTvHelpId = (TextView) mParentView.findViewById(R.id.tv_help_id);
        mTvHelpHigh = (TextView) mParentView.findViewById(R.id.tv_help_high);
        mTvHelpDistance = (TextView) mParentView.findViewById(R.id.tv_help_distance);
        mTvHelpFloor = (TextView) mParentView.findViewById(R.id.tv_help_floor);
        mTvHelpTemperature = (TextView) mParentView.findViewById(R.id.tv_help_temperature);
        mTvHelpError = (TextView) mParentView.findViewById(R.id.tv_help_error);
        mHelpInfoParent = (LinearLayout) mParentView.findViewById(R.id.layout_help_parent);
        mTvEnter = (TextView) mParentView.findViewById(R.id.tv_call_police);
        mTvExit = (TextView) mParentView.findViewById(R.id.tv_cancel_police);
        mLayoutEnter = (RelativeLayout) mParentView.findViewById(R.id.layout_enter);
        mLayoutExit = (RelativeLayout) mParentView.findViewById(R.id.layout_exit);
        mIvMy = (CircleImageView) mParentView.findViewById(R.id.iv_my_head);
        mIvHim = (CircleImageView) mParentView.findViewById(R.id.iv_help_head);
        mBtnFinishHelp = (TextView) mParentView.findViewById(R.id.tv_finish_help);
        mBtnStopHelp = (TextView) mParentView.findViewById(R.id.tv_stop_help);
        mBtnVideo = (RelativeLayout) mParentView.findViewById(R.id.btn_open_video);
        mFirstFloor = (Spinner) mParentView.findViewById(R.id.spinner_original_floor);
        mFloorHigh = (Spinner) mParentView.findViewById(R.id.spinner_floor_high);
        mFirstFloor.setSelection(3);
        mFirstFloor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                AllData.FIRST_FLOOR = (int) getNum(mListFirstFloor.get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mFloorHigh.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                AllData.FLOOR_HIGH = (int) getNum(mListFloorHigh.get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mBtnStopHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editHelp(true);
                callHelp();
            }
        });
        mBtnVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AllData.isToHelp){
                    String roomId = StringUtils.getRandomString(15);
                    Map<String, Object> map = new HashMap<>();
                    map.put("soid", AllData.outPolice_id);
                    map.put("goid", AllData.callHelpModel.getOid());
                    map.put("roomId", roomId);
                    JSONObject jsonObject = new JSONObject(map);
                    mSocket.emit("video", jsonObject);
                }
            }
        });
        mBtnFinishHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editHelp(false);
            }
        });
        mTvExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvEnter.setClickable(true);
                mTvExit.setClickable(false);
                mLayoutEnter.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                mLayoutExit.setBackgroundColor(getResources().getColor(R.color.gray));
                //SendData.data = SendData.sendCancelPoliceData();
                //SendData.needSend = true;
            }
        });
        mTvEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvEnter.setClickable(false);
                mTvExit.setClickable(true);
                mLayoutEnter.setBackgroundColor(getResources().getColor(R.color.gray));
                mLayoutExit.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                //SendData.data = SendData.sendEnterPoliceData();
                //SendData.needSend = true;
            }
        });
    }

    private void callHelp(){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uid", AllData.callHelpModel.getUid());
        map.put("mid", AllData.callHelpModel.getMid());
        map.put("oid", AllData.callHelpModel.getOid());
        map.put("high", AllData.callHelpModel.getHigh());
        map.put("fid", AllData.callHelpModel.getFid());
        map.put("name", AllData.callHelpModel.getName());
        map.put("image", AllData.callHelpModel.getUserImage());
        JSONObject jsonObject = new JSONObject(map);
        mSocket.emit("help", jsonObject);
    }

    private void editHelp(boolean isStop){
        AllData.isToHelp = false;
        if(isStop){
            SendData.data = SendData.sendStopHelp();
        }else {
            SendData.data = SendData.sendFinishHelp();
        }
        SendData.needSend = true;
        cancelCallHelp();
    }

    private void cancelCallHelp(){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", AllData.callHelpModel.get_id());
        map.put("oid", AllData.callHelpModel.getOid());
        map.put("fid", AllData.callHelpModel.getFid());
        JSONObject jsonObject = new JSONObject(map);
        mSocket.emit("cancelHelp", jsonObject);
        AllData.isFirstLoad = true;
    }

    private void initData() {
        if(HelpModel.needChange) {
            HelpModel.needChange = false;
            mTvHighId.setText(AllData.userModel.getUsername());
            mTvHighHigh.setText(getNum(AllData.helpModel.getMachineHigh()) + "");
            mTvHighTemperature.setText(getNum(AllData.helpModel.getMachineTemp()) + "");
//          mTvHighFloor.setText(AllData.helpModel.getNowFloor() + "");
            mTvHighFloor.setText(AllData.helpModel.getMachinePressure());
            if(AllData.isToHelp){
                if(AllData.isFirstLoad) {
                    mIvMy.setImageBitmap(AllData.userBitmap.get(AllData.userModel.get_id()));
                    mHelpInfoParent.setVisibility(View.VISIBLE);
                    for (int i = 0; i < AllData.outPoliceModels.size(); i++) {
                        if (AllData.outPoliceModels.get(i).getMid().equals(AllData.callHelpModel.getMid())) {
                            mIvHim.setImageBitmap(AllData.userBitmap.get(AllData.outPoliceModels.get(i).getUid()));
                            mTvHelpId.setText(AllData.outPoliceModels.get(i).getUserName());
                            break;
                        }
                    }
                    AllData.isFirstLoad = false;
                }
                if (HelpModel.isWhat == 2) {
                    if(getNum(AllData.helpModel.getHelpError()) < 10) {
//                        double distance = getNum(AllData.helpModel.getHelpDistance()) / 1200;
                        double d = getNum(AllData.helpModel.getHelpDistance());
                        if(d<1000){
                            mTvHelpDistance.setBackgroundColor(getResources().getColor(R.color.lawngreen));
                            mTvHelpDistance.setText("     5m     ");
                        }else  if(d<2500&&d>1200){
                            mTvHelpDistance.setBackgroundColor(getResources().getColor(R.color.chartreuse));
                            mTvHelpDistance.setText("    10m    ");
                        }else if(d>3000) {
                            mTvHelpDistance.setBackgroundColor(getResources().getColor(R.color.red));
                            mTvHelpDistance.setText("    15m    ");
                        }
//                        BigDecimal b = new BigDecimal(distance);
//                        distance = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
//                        AllData.helpModel.setHelpDistance(distance + "");
                        if ((getNum(AllData.helpModel.getHelpDistance()) + 2 > AllData.helpDistance) ||
                                (getNum(AllData.helpModel.getHelpDistance()) - 2) < AllData.helpDistance) {
                                Map<String, Object> map = new HashMap<>();
                                map.put("distance", getNum(AllData.helpModel.getHelpDistance()));
                                map.put("id", AllData.callHelpModel.get_id());
                                map.put("fid", AllData.userModel.getFirecompany_id());
                                JSONObject jsonObject = new JSONObject(map);
                                mSocket.emit("upHelpDistance", jsonObject);
                        }
                        mTvHelpHigh.setText(getNum(AllData.helpModel.getHelpHigh()) + "");
//                        mTvHelpError.setText(getNum(AllData.helpModel.getHelpError()) + "");
//                        mTvHelpDistance.setText(getNum(AllData.helpModel.getHelpDistance()) + "");
                    } else {
//                        mTvHelpDistance.setText("--");
//                        mTvHelpError.setText("10.0");
                    }
                    //TODO 修改为楼层显示
                    //mTvHelpPressure.setText(getNum(AllData.helpModel.getHelpPressure()) + "");
                    mTvHelpTemperature.setText(getNum(AllData.helpModel.getHelpTemp()) + "");
                }
            }else {
                mHelpInfoParent.setVisibility(View.GONE);
            }
        }
    }

    private class SetDataThread extends Thread{
        public void run(){
            while (true)
                if(HelpModel.needChange){
                    Message message = new Message();
                    message.what = 0;
                    mHandler.sendMessage(message);
                }
        }
    }

    public static double getNum(String str){
        char[] b = str.toCharArray();
        String result = "";
        if(str.equals("")){
            return -1;
        }
        for (int i = 0; i < b.length; i++) {
            if (("0123456789.-").indexOf(b[i] + "") != -1) {
                result += b[i];
            }
        }
        if(result.equals("")){
            return 999999999;
        } else {
            return Double.valueOf(result).doubleValue();
        }
    }


    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = UsbApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }
}
